/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 19:46:50
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.action.AbsSdkDoAction;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.MenuInfoManager;
import cn.cmcc.online.smsapi.sdk.db.ParseItemManager;
import cn.cmcc.online.smsapi.sdk.db.bizport.BizportDBManager;
import cn.cmcc.online.smsapi.sdk.db.entity.EmergencyManger;
import cn.cmcc.online.smsapi.sdk.db.entity.JarSubInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.JarSubInfoManager;
import cn.cmcc.online.smsapi.sdk.db.entity.MatchCacheManager;
import cn.cmcc.online.smsapi.sdk.db.entity.MenuInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.RecordActionManager;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.db.entity.UpdateTaskManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerResposeParseUtil;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.net.util.SigntureUtil;
import cn.cmcc.online.smsapi.sdk.queue.EmergencyQueue;
import cn.cmcc.online.smsapi.util.ParseManager;
import cn.cmcc.online.smsapi.util.SdkParamUtil;

public class JarSubCheckQueue extends Thread {
    private static boolean isRun = false;// 是否正在下载中
    /* SDK-442 huangzhiqiang 20160518 start */
    private static long mLastUpdateTime = 0; // 最后一次执行MatchCacheManager.resetParseFailMsgLastTime(0)方法的时间
    private static long mDefaultUpdateLastParseTimeCycle = 10 * Constant.MINUTE; // 默认为10分钟可以执行一次MatchCacheManager.resetParseFailMsgLastTime(0)方法
    /* SDK-442 huangzhiqiang 20160518 end */
    /* SDK-579 huangzhiqiang 20160805 start */
    private static int JAR_UPDATE_LIMIT = 20;
    /* SDK-579 huangzhiqiang 20160805 start */
    
    /*SDK-747 zhaojiangwei 20160330 start */
    public static boolean mSDKLoadCompleted = false;
    /*SDK-747 zhaojiangwei 20160330 end */
    
    public synchronized static void runJarSubCheckQueue() {
        if (isRun == false) {
            isRun = true;
            // 当队列线程序未运行时,才运行
            JarSubCheckQueue queue = new JarSubCheckQueue();
            /*SDK-426 hewengao 20160506 start */
            queue.setPriority(Thread.MIN_PRIORITY);
            /*SDK-426 hewengao 20160506 end */
            queue.start();
        }
    }

    @Override
    public void run() {
        try {
            /*SDK-426 hewengao 20160506 start */
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
            /*SDK-426 hewengao 20160506 end */

            /* SDK-579 huangzhiqiang 20160805 start */
            // 延时20秒后执行更新，积累20秒内所需更新的jar包数据后再发送更新请求，以减少请求次数
            Thread.sleep(20000);
            /* SDK-579 huangzhiqiang 20160805 end */

            runTask();
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue run error", e);
        } finally {
            isRun = false;
        }
    }

    public void runTask() {
        try {
        	int type = SysParamEntityManager.getIntParam(Constant.getContext(), Constant.ONLINE_UPDATE_SDK);
            KeyManager.initAppKey(); 
        	if(("5Mj22a4wHUAWEICARD".equals(KeyManager.channel) && type==0)  || !NetUtil.checkAccessNetWork(2)){ 
        		//华为卡夹受ONLINE_UPDATE_SDK控制，//其他受网络开关控制
        		return;
        	}
            checkJarsUpdate(true, true);

            if (type == 0) {
                return;
            }
            // 检测并执行是否有未完成的更新
            /* SDK-397 huangzhiqiang 20160524 start */
            UpdateTaskManager.doTask(UpdateTaskManager.TaskGroup.UPDATE_PUBINFO);
            /* SDK-397 huangzhiqiang 20160524 end */
            InitUtil.postConutData();//统计数据上传
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue runTask error", e);
        }
    }

    // 检查算法包更新
    public static void checkJarsUpdate(final boolean isDownload, boolean checkCycle) {
        try {
            /*SDK-747 zhaojiangwei 20160330 start */
            if (!NetUtil.isEnhance() && !mSDKLoadCompleted) {
                return;
            }
            /*SDK-747 zhaojiangwei 20160330 end */
            
            // 如果没有main包，在数据库插入一条记录
            checkMain();

            /* SDK-579 huangzhiqiang 20160805 start */
            // 获取需要检查更新的已使用jar包数据
            long updateTime = checkCycle ? getJarUpdateTime() : Long.MAX_VALUE;
            List<JarSubInfo> jarSubInfoList = JarSubInfoManager.queryIsUseJarSubInfoByUpdateTime(updateTime);
            if (jarSubInfoList == null || jarSubInfoList.isEmpty()) {
                return;
            }

            int jarCount = jarSubInfoList.size();
            double updateCount = Math.ceil(Double.parseDouble(String.valueOf(jarCount)) / JAR_UPDATE_LIMIT);
            for (int i = 0; i < updateCount; i++) {
                int start = (i * JAR_UPDATE_LIMIT);
                int end = (((i + 1) == updateCount) ? jarCount : ((i + 1) * JAR_UPDATE_LIMIT));
                checkJarsUpdateByNet(jarSubInfoList.subList(start, end), isDownload);
            }

            // 更新jars完成检测时间
            SysParamEntityManager.setParam("JARS_UPDATE_TIME", String.valueOf(System.currentTimeMillis()));
            // 清除上报统计
            RecordActionManager.deleteAll();
            EmergencyQueue.runEmergencyQueue();
            if (isDownload) {
                downloadJars();
            }
            /* SDK-579 huangzhiqiang 20160805 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue checkJarsUpdate error", e);
        }
    }

    /* SDK-579 huangzhiqiang 20160805 start */
    private static void checkJarsUpdateByNet(final List<JarSubInfo> jarSubInfoList, final boolean isDownload) {
        try {
            // 生成请求的报文
            String updateJarsRequest = ServerUtil.getUpdateJarsRequest(jarSubInfoList,
                    RecordActionManager.queryActionRecord(), getEmVer());
            /* SDK-504 huangzhiqiang 20160623 start */
            if (StringUtils.isNull(updateJarsRequest)) {// 如果没有需要检测的包，则返回
                return;
            }
            /* SDK-504 huangzhiqiang 20160623 end */

            XyCallBack callback = new XyCallBack() {
                @Override
                public void execute(Object... obj) {
                    try {
                        if (obj == null || obj.length < 2 || ((Integer) obj[0] != 0)) {
                            return;
                        }
                        String response = obj[1].toString();
                        LogManager.d(Constant.TAG, "checkJarsUpdateByNet response=", response);
                        handleJarsUpdateResponse(response);
                    } catch (Throwable e) {
                        LogManager.e(Constant.TAG, "JarSubCheckQueue checkJarsUpdateByNet callback error", e);
                    }
                }
            };
            NetUtil.executeHttpRequest(0, updateJarsRequest, callback, NetUtil.getPopupServiceUrl()
                    + NetUtil.UpdateRecognitionJarRequest, null, false);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue checkJarsUpdateByNet error", e);
        }
    }

    /**
     * 获取应急版本号
     * 
     * @return
     */
    private static String getEmVer() {
        String emVer = SysParamEntityManager.getStringParam(Constant.getContext(), "EM_VERSION");
        if (StringUtils.isNull(emVer)) {
            emVer = "-1";
        }
        return emVer;
    }

    /**
     * 处理算法包更新响应报文，入库算法包信息及紧急处理指令
     * 
     * @param response
     * @throws Throwable
     */
    private static void handleJarsUpdateResponse(String response) throws Throwable {
        // 解析返回的报文
        Map<String, Object> updateDataMap = ServerResposeParseUtil.parseJarsUpdateRespose(response);
        if (updateDataMap == null) {// 返回的报文没有解析成功则
            return;
        }
        long currentTime = System.currentTimeMillis();
        // 将返回的信息更新到tb_jar_list表
        Object updateJarsObj = updateDataMap.get("updataJars");
        if (updateJarsObj != null) {
            JSONObject updateJar = null;
            JSONArray updateJars = (JSONArray) updateJarsObj;
            for (int i = 0; i < updateJars.length(); i++) {
                updateJar = updateJars.getJSONObject(i);
                JarSubInfoManager.updateJarSubInfo(updateJar.getString("name"), updateJar.getString("version"),
                        updateJar.getString("url"), System.currentTimeMillis(), JarSubInfoManager.NOTFINISH,
                        updateJar.getInt("delayStart") + currentTime, updateJar.getInt("delayEnd") + currentTime,
                        updateJar.optString("pver"));
            }
        }
        if (updateDataMap.containsKey("emergencyArray")) {
            JSONArray emergencyArray = (JSONArray) updateDataMap.get("emergencyArray");
            EmergencyManger.insertOrUpdateEmergency(emergencyArray);
        }
    }

    /**
     * 下载算法包及更新算法包更新次数(受网络开关控制)
     * 
     * @param jarSubInfoList
     */
    private static void downloadJars() {
        // 受网络开关控制
        if (!NetUtil.checkAccessNetWork(2)) {
            return;
        }
        List<JarSubInfo> jarSubInfoList = JarSubInfoManager.queryNeedDownloadJarInfo();
        if (jarSubInfoList == null || jarSubInfoList.isEmpty()) {
            return;
        }
        /*ONEPLUSCII-98 songzhirong 20161226 start*/
        boolean isCallUpdateParseVersion = false;
        String config =  DuoquUtils.getSdkDoAction().getConfig(AbsSdkDoAction.CONFIG_NOTIFY_ALL_ALGORITHM, null);
        if(StringUtils.isNull(config)||"true".equals(config)){
        	isCallUpdateParseVersion = true;
        }
        for (JarSubInfo info : jarSubInfoList) {
            downloadJarInfo(info, false);
            if(!StringUtils.isNull(info.name)&&info.name.startsWith("PU")){
            	isCallUpdateParseVersion = true;
            }
        }
        if(isCallUpdateParseVersion){
            updateParseVersion();
        }
    
    }

       private static long getJarUpdateTime() {
        int day = SysParamEntityManager.getIntParam(Constant.getContext(), Constant.ONLINE_UPDATE_SDK_PERIOD);
        if (day < 1) {
            day = 1;
        }
        return System.currentTimeMillis()
                - DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_JAR_FILE_UPDATE_CYCLE,
                        Constant.jarsubFileUpdatePrio * day);
    }
    /* SDK-579 huangzhiqiang 20160805 end */

    public static void downloadJarInfo(final JarSubInfo jarSubInfo,boolean downloadNow) {
        try {

            long nowTime = System.currentTimeMillis();
            // 下载状态为未下载和时间合符要求的才会触发下载
            if (jarSubInfo.status == JarSubInfoManager.NOTFINISH && (downloadNow || jarSubInfo.delaystart <= nowTime)) {
                if (!StringUtils.isNull(jarSubInfo.url)) {
                    /* SDK-782 huangzhiqiang 20170519 start */
                    String tempUpdatePath = Constant.getTempUpdatePath();
                    String zipName = jarSubInfo.name + ".zip";
                    /* SDK-396 huangzhiqiang 20160418 start */
                    if(FileUtils.downFile(jarSubInfo.url, tempUpdatePath, zipName) == -1){
                        LogManager.d("JarSubInfo", zipName, "下载失败");
                        return;
                    }
                    LogManager.d("JarSubInfo", "成功下载", zipName);

                    if(!XyUtil.upZipFile(tempUpdatePath + zipName, tempUpdatePath)){
                        LogManager.d("JarSubInfo", zipName,"解压失败");
                        return;
                    }

                    String sqlName = jarSubInfo.name + ".sql";
                    String sqlPath = tempUpdatePath + sqlName;
                    File sqlFile = new File(sqlPath);
                    if (sqlFile.exists()) {
                        LogManager.d("JarSubInfo", "成功解压" , zipName);
                        String verifyName = jarSubInfo.name + ".txt";
                        String fileMd5 = StringUtils.getFileMD5(sqlPath);
                        String verifyMd5 = SigntureUtil.getVerifyCode(tempUpdatePath, verifyName);
                        if (LogManager.debug) {
                            LogManager.d("JarSubInfo", "fileMd5 =" ,fileMd5);
                            LogManager.d("JarSubInfo", "verifyMd5 =" , verifyMd5);
                        }

                        if (!fileMd5.equals(verifyMd5)) {
                            deleteTempParseFile(jarSubInfo.name);
                            LogManager.d("JarSubInfo", sqlName ,"fileMd5不匹配");
                            return;
                        }

                        deleteTimeOutMatchId(jarSubInfo.name);
                        // 更新sql
                        if (!updateParse(Constant.getContext(), sqlFile)) {
                            deleteTempParseFile(jarSubInfo.name);
                            LogManager.d("JarSubInfo", sqlName ,"更新sql执行失败");
                            return;
                        }
                    }
                    /* SDK-396 huangzhiqiang 20160418 end */

                    // 将parse_update_temp文件夹下的jar、idx、txt、version.txt文件复制到parse文件夹并删掉旧的dex和jar文件
                    updateParseFile(jarSubInfo.name, jarSubInfo.version);
                    /* SDK-782 huangzhiqiang 20170519 end */

                    JarSubInfoManager.updateLastLoadTime(jarSubInfo.name, JarSubInfoManager.FINISH);

                    /* SDK-654 hewengao 20161026 start */
                    FileUtils.mCacheJarFile.put(jarSubInfo.name, jarSubInfo.name + "_" + jarSubInfo.version + ".jar");
                   //XyUtil.chmod("640", Constant.getPARSE_PATH()+newName);
                    /*SDK-654 hewengao 20161026 end*/
                    if ("parseUtilMain".equals(jarSubInfo.name) || "ParseSimpleBubbleUtil".equals(jarSubInfo.name)) {
                        DexUtil.removeClassLoaderBySubname(jarSubInfo.name);
                        DexUtil.init();
                    } else {
                    	/*SDK-667 zhaojiangwei 20161108 start*/
                        if ("OnlineUpdateCycleConfig".equals(jarSubInfo.name)) {
                        	DexUtil.removeClassLoaderBySubname(jarSubInfo.name);
                            DexUtil.initOnlineUpdateCycleConfig();
                        } else{
                              /*SDK-654 hewengao 20161026 start*/
                            DexUtil.getClassBymap(null, "cn.com.xy.sms.sdk.Iservice."+jarSubInfo.name, true);
                             /*SDK-654 hewengao 20161026 end*/
                        }
                        /*SDK-667 zhaojiangwei 20161108 end*/
                    }

                    /* SDK-782 huangzhiqiang 20170519 start */
                    // 删除parse_update_temp文件夹下的临时文件
                    deleteTempParseFile(jarSubInfo.name);
                    /* SDK-782 huangzhiqiang 20170519 end */

                    /* SDK-560 huangzhiqiang 20160725 start */
//                    // 算法包升级，历史数据重新扫描
//                    String key = "BEFORE_HAND_PARSE_SMS_TIME";
//                    SysParamEntityManager.setParam(key, System.currentTimeMillis() + "");
                    /* SDK-560 huangzhiqiang 20160725 end */

                    /* SDK-442 huangzhiqiang 20160518 start */
                    if (System.currentTimeMillis() > mLastUpdateTime + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, mDefaultUpdateLastParseTimeCycle)) {
                        // 重置不识别的短信的最后识别时间为0，以便不识别的短信能及时进入识别流程重新识别
                        MatchCacheManager.resetLastParseTime(0);
                        mLastUpdateTime = System.currentTimeMillis();
                    }
                    /* SDK-442 huangzhiqiang 20160518 end */

                    /* SDK-556 huangzhiqiang 20160722 start */
                    DuoquUtils.getSdkDoAction().logInfo(Constant.TAG, String.format("download %s complete", jarSubInfo.name), null); 
                    /* SDK-556 huangzhiqiang 20160722 end */
                }
//                updateParseVersion();
            } else {
                if (jarSubInfo.status == JarSubInfoManager.FINISH) {
                    if (LogManager.debug) {
//                        LogManager.i("JarSubInfo", jarSubInfo.name + "已经下载，不需要下载" + " url=" + jarSubInfo.url);
                    }
                } else {
                    if (LogManager.debug) {
//                        LogManager.i("JarSubInfo", "当前时间不在下载区域内，不下载name=" + jarSubInfo.name + " url=" + jarSubInfo.url);
                    }
                }
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue downloadJarInfo error", e);
        }
    }
    
    //删除超时的matchId脚本
    public static void deleteTimeOutMatchId(final String name) {
        try {
            if (StringUtils.isNull(name)) {
                return;
            }
            ParseItemManager.deleteTimeOutMatchId(name.substring(2));
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue deleteTimeOutMatchId error", e);
        }
    }

    public static void updateParseVersion() {
        try {
            int version = ParseManager.getParseVersion(Constant.getContext(), null);
            version = version + 1;
            SdkParamUtil.setParamValue(Constant.getContext(), "PARSE_VERSION", version + "");
            /*SDK-715 songzhirong 20170105 start*/
            long addVersionChangeTime = SysParamEntityManager.getLongParam(Constant.CONFIG_NOTIFY_TIMEMS,Constant.addVersionChangeTime,Constant.getContext());
            if (System.currentTimeMillis() >= (Constant.lastVersionChangeTime + addVersionChangeTime)) {
            /*SDK-715 songzhirong 20170105 end*/
            	DuoquUtils.getSdkDoAction().parseVersionChange(Constant.getContext(),version);
                Constant.lastVersionChangeTime = System.currentTimeMillis();
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue updateParseVersion error", e);
        }
    }

    /* SDK-782 huangzhiqiang 20170519 start */
    public static void handleLine(String line, SQLiteDatabase db) {
        if (StringUtils.isNull(line)) {
            return;
        }
        ContentValues values = new ContentValues();
        String remain = line;
        String scene_id = remain.substring(0, remain.indexOf(","));
        remain = remain.substring(remain.indexOf(",") + 1, remain.length());
        String match_id = remain.substring(0, remain.indexOf(","));
        remain = remain.substring(remain.indexOf(",") + 1, remain.length());
        String regex_type = remain.substring(0, remain.indexOf(","));
        remain = remain.substring(remain.indexOf(",") + 1, remain.length());
        String version_code = remain.substring(0, remain.indexOf(","));
        String regex_text = remain.substring(remain.indexOf(",") + 1, remain.length());

        values.put(ParseItemManager.SCENE_ID, scene_id);
        values.put(ParseItemManager.MATCH_ID, match_id);
        values.put(ParseItemManager.REGEX_TYPE, regex_type);
        values.put(ParseItemManager.VERSION_CODE, version_code);
        values.put(ParseItemManager.REGEX_TEXT, regex_text);
        long flag = 0;
        flag = db.update(ParseItemManager.TABLE_NAME, values, "scene_id= ? and match_id =?", new String[] { scene_id,
                match_id });
        if (flag == 0) {
            flag = db.insert(ParseItemManager.TABLE_NAME, null, values);
        }
    }
    /* SDK-782 huangzhiqiang 20170519 end */

    /* SDK-396 huangzhiqiang 20160418 start */
    public static boolean updateParse(Context context, File file) {
        if(file == null || !file.exists()){
            return false;
        }
        SQLiteDatabase db = null;
        BufferedReader bw = null;
        java.io.LineNumberReader r = null;
        try {
            bw = new BufferedReader(new FileReader(file));
            r = new LineNumberReader(bw);
            String line = null;
            db = BizportDBManager.getSQLiteDatabase();
            db.beginTransaction();
            while ((line = r.readLine()) != null) {
                handleLine(line, db);
            }
            /* SDK-782 huangzhiqiang 20170519 start */
            db.setTransactionSuccessful();
            /* SDK-782 huangzhiqiang 20170519 end */
            return true;
        } catch (Throwable e) {
            LogManager.e("JarSubInfo", "JarSubCheckQueue updateParse error", e);
        } finally {
            try {
                LogManager.d("JarSubInfo", "updateParse deleteAllFile filePath=" , file.getPath());
                // 删除数据文件
                FileUtils.deleteAllFile(file);
            } catch (Throwable ex) {
                LogManager.e(Constant.TAG, "JarSubCheckQueue updateParse deleteAllFile error", ex);
            }
            /* SDK-782 huangzhiqiang 20170519 start */
            BizportDBManager.closeDB(null, false, r, bw, null);
            if (db != null) {
                try {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                } catch (Throwable e) {
                    LogManager.w(Constant.TAG, "JarSubCheckQueue updateParse error", e);
                } finally {
                    DBManager.close(db);
                }
            }
            /* SDK-782 huangzhiqiang 20170519 end */
        }
        return false;
    }
    /* SDK-396 huangzhiqiang 20160418 end */

    public static void checkMain() {
       
        if (ParseManager.isInitData()) {
            JarSubInfo jarSubInfo = JarSubInfoManager.queryJarSubInfo("parseUtilMain");
            if (jarSubInfo == null) {
                JarSubInfoManager.insertOrUpdateJarSubInfo("parseUtilMain", "-1", JarSubInfoManager.USED);
//                JarSubInfoManager.insertOrUpdateJarSubInfo("ParseHelper", "-1", JarSubInfoManager.USED);
                JarSubInfoManager.insertOrUpdateJarSubInfo("ScenesScanner", "-1", JarSubInfoManager.USED);
                JarSubInfoManager.insertOrUpdateJarSubInfo("ParseSimpleBubbleUtil", "-1", JarSubInfoManager.USED);
                JarSubInfoManager.insertOrUpdateJarSubInfo("ParseUtilBubble", "-1", JarSubInfoManager.USED);
            }
        }
    }

    /**
     * 检查算法是否有更新
     * 
     * @return true有，false没有
     */
    public static boolean checkJarUpdate(final Map<String, String> extend,final boolean isDownload, boolean checkCycle) {
        try {
            checkMain();
            checkJarsUpdate(isDownload, checkCycle);
            /* SDK-579 huangzhiqiang 20160805 start */
            return JarSubInfoManager.needUpdateJar();
            /* SDK-579 huangzhiqiang 20160805 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue checkJarUpdate error", e);
        }
        return false;
    }
    
    /**
     * 检查算法是否有更新,只检查数据库里是否有还没下载的
     * 
     * @return true有，false没有
     */
    public static boolean checkDatabaseJarUpdate(final Map<String, String> extend) {
        try {
            /* SDK-579 huangzhiqiang 20160805 start */
            return JarSubInfoManager.needUpdateJar();
            /* SDK-579 huangzhiqiang 20160805 end */
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue checkDatabaseJarUpdate error", e);
        }
        return false;
    }

    public static void updateJarPackageSyn(final Map<String, String> extend, final XyCallBack xyCallBack) {
        try {
            checkMain();
            List<JarSubInfo> jarSubInfoList = JarSubInfoManager.queryAllJarSubInfo();
            boolean hasDownLoad = false;
            if (jarSubInfoList != null && !jarSubInfoList.isEmpty()) {
                int size = jarSubInfoList.size();
                for (int i = 0; i < size; i++) {
                    JarSubInfo jarSubInfo = jarSubInfoList.get(i);
                    downloadJarInfo(jarSubInfo,true);
                    hasDownLoad = true;
                }
            }
            if(hasDownLoad){
            	 updateParseVersion();
            }
         
            MenuInfo menuInfo = MenuInfoManager.queryMenuInfo("menuMain");
            if (!MenuInfoManager.checkMenuUpdate(menuInfo) && !checkDatabaseJarUpdate(extend)) {// 菜单和jar包都没有更新，说明更新成功
                XyUtil.doXycallBack(xyCallBack, "1");
            } else {
                // 更新失败
                XyUtil.doXycallBack(xyCallBack, "0");
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "JarSubCheckQueue updateJarPackageSyn error", e);
        }
    }

    /* SDK-782 huangzhiqiang 20170519 start */
    /**
     * 将parse_update_temp文件夹下的jar、idx、txt、version.txt文件复制到parse文件夹并删掉旧的dex和jar文件
     * 
     * @param parseName
     * @param parseVersion
     * @return
     */
    private static void updateParseFile(String parseName, String parseVersion) {
        String tempUpdateFolderPath = Constant.getTempUpdatePath();
        String parseFolderPath = Constant.getPARSE_PATH();
        String tempFileNamePrefix = tempUpdateFolderPath + parseName;
        String fileNamePrefix = parseFolderPath + parseName;
        // 从parse_update_temp文件夹下复制jar到parse文件夹
        FileUtils.copyFile(tempFileNamePrefix + ".jar", fileNamePrefix + "_" + parseVersion + ".jar", true);
        // 从parse_update_temp文件夹下复制idx到parse文件夹
        FileUtils.copyFile(tempFileNamePrefix + ".idx", fileNamePrefix + ".idx", true);
        // 从parse_update_temp文件夹下复制txt到parse文件夹
        FileUtils.copyFile(tempFileNamePrefix + ".txt", fileNamePrefix + ".txt", true);
        // 从parse_update_temp文件夹下复制version.txt到parse文件夹
        FileUtils.copyFile(tempUpdateFolderPath + "version.txt", parseFolderPath + "version.txt", true);
        // 删掉旧的jar和dex
        FileUtils.deleteFile(parseFolderPath, parseName + "_", ".jar", parseName + "_" + parseVersion + ".jar");
        FileUtils.deleteDex(parseName + "_", ".dex", parseName + "_" + parseVersion + ".dex");
    }

    /**
     * 删除parse_update_temp文件夹下的临时文件
     * 
     * @param parseName
     */
    private static void deleteTempParseFile(String parseName) {
        String tempUpdateFolderPath = Constant.getTempUpdatePath();
        String tempFileNamePrefix = tempUpdateFolderPath + parseName;
        FileUtils.deleteFile(tempFileNamePrefix + ".zip");
        FileUtils.deleteFile(tempFileNamePrefix + ".jar");
        FileUtils.deleteFile(tempFileNamePrefix + ".idx");
        FileUtils.deleteFile(tempFileNamePrefix + ".txt");
        FileUtils.deleteFile(tempUpdateFolderPath + "version.txt");
    }
    /* SDK-782 huangzhiqiang 20170519 end */
}
